package com.ly.wxstore.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ly.wxstore.entity.WeixinUserInfo;
import com.ly.wxstore.service.WeixinUserInfoService;
import com.ly.wxstore.service.account.ShiroDbRealm.ShiroUser;

/**
 * 
 * @author Peter
 *
 */
@Controller
@RequestMapping("/")
public class IndexController {
	
	private static Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	@Autowired
	private WeixinUserInfoService weixinUserInfoService;

    @RequestMapping
    public String getIndexPage(Model model) {
    	logger.info("index");
    	
    	ShiroUser user = getCurrentUser();
    	String openId = user.getOpenid();
    	WeixinUserInfo weixinUserInfo = weixinUserInfoService.receiveWeixinUserInfoByOpenId(openId);
    	
    	if(weixinUserInfo!=null){
			model.addAttribute("headimgurl", weixinUserInfo.getHeadimgurl());
			model.addAttribute("nickName", weixinUserInfo.getNicknameForBase64Decoder());
		}
    	
    	
        return "index";
    }
    
    /**
	 * 使用Ehcache缓存 ShiroUse 信息，如果缓存失效，user里面的数据将会丢失
	 * @return
	 */
	private ShiroUser getCurrentUser() {
		Subject currentUser = SecurityUtils.getSubject();
		if ( currentUser.isAuthenticated() ) {
			logger.info("-----getCurrentUser 已经录系统----");
		}else{
			logger.info("-----getCurrentUser 未登录系统----");
		}
		
		// 使用Ehcache缓存 ShiroUse 信息，如果缓存失效，user里面的数据将会丢失
		ShiroUser user = (ShiroUser) currentUser.getPrincipal();
		if(user!=null){
			logger.info("-----getCurrentUser 当前登录的用户信息---->>\n            "+user.print());
		}else{
			logger.info("-----getCurrentUser 当前登录的用户信息  --  null  ---->>");
		}
		return user;
	}
}
